<?php
header('Content-Type: text/xml');

$dbhost = "127.0.0.1";
$dbuser = "root";
$dbpasswd = "123456";

function err_resp()
{
	echo  '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
		<document type="freeswitch/xml">
		  <section name="result">
		    <result status="not found" />
		  </section>
		</document>';
	exit;
}

function cidr_match($ip, $range)
{
	$arr = explode('/', $range);
	if(count($arr)==1)
	{
		$subnet = $arr[0];
		$bits = 32;
	}
	else if(count($arr) == 2)
	{
		$subnet = $arr[0];
		$bits = intval($arr[1]);
		if($bits <=0 || $bits > 32)
			return FALSE;
	}
	else
	{
		return FALSE;
	}
	$ip = ip2long($ip);
	if ($ip == -1 || $ip === FALSE) {
		return FALSE;
	}
        $subnet = ip2long($subnet);
	if ($subnet == -1 || $subnet === FALSE) {
		return FALSE;
	}
        $mask = -1 << (32 - $bits);
        $subnet &= $mask;
        return ($ip & $mask) == $subnet;
}

var_dump($_POST);

if(!array_key_exists("section", $_POST) 
|| !array_key_exists("action", $_POST) 
|| !array_key_exists("user", $_POST) 
|| !array_key_exists("sip_auth_method", $_POST) 
|| !array_key_exists("ip", $_POST) 
|| !array_key_exists("domain", $_POST))
{
	//not sip register request
	err_resp();
}

$section = $_POST["section"];
$action = $_POST["action"];
$user = $_POST["user"];
$method = $_POST["sip_auth_method"];
$regip = $_POST["ip"];
$domain = $_POST["domain"];

//error_log("recv request: section[$section] action[$action] user[$user] method[$method] ip[$regip] domain[$domain]");

if($section != "directory" || 
		$action != "sip_auth" ||
		$method != "REGISTER")
{
	//not sip register request
	err_resp();
}

$con = mysql_connect($dbhost,$dbuser,$dbpasswd);
if(!$con)
{
	error_log("connect mysql failed");
	err_resp();
}

mysql_select_db("cc", $con);

$result = mysql_query("SELECT ip, password, name FROM agents where number=$user and type=0");
if(!$result)
{
	error_log("mysql query failed");
	mysql_close($con);
	err_resp();
}

$row=mysql_fetch_row($result);
if(!$row)
{
	error_log("No sip agent [$user]");
	mysql_close($con);
	err_resp();
}

$sip_passwd = $row[1];
$name = $row[2];
if(!$sip_passwd || strlen($sip_passwd)<=0)
{
	error_log("This user[$user] have not password, can't register");
	mysql_close($con);
	err_resp();
}

$ranges = $row[0];
if($ranges && strlen($ranges)>0)
{
	$ips = explode(",", $ranges);
	$ip_count = count($ips);

	for($i=0; $i<$ip_count; $i++)
	{
		$r = $ips[$i];
		//error_log("ip :".$r);
		if(cidr_match($regip, $r))
		{
			//error_log("client ip [$regip] match [$r] ok");
			break;
		}
	}
	if($i==$ip_count)
	{
		error_log("Clinet ip [$regip] auth failed, user: $user");
		mysql_close($con);
		err_resp();
	}
}

$tmp = "$user:$domain:$sip_passwd";
$hash = md5($tmp);
//error_log("tmp:$tmp hash:$hash");

$resp = '<document type="freeswitch/xml">
  <section name="directory">
    <domain name="'.$domain.'">
      <params>
        <param name="dial-string" value="{presence_id=${dialed_user}@${dialed_domain}}${sofia_contact(${dialed_user}@${dialed_domain})}"/>
      </params>
      <groups>
        <group name="default">
         <users>
          <user id="'.$user.'" cacheable="60000">
            <params>
		<param name="a1-hash" value="'.$hash.'"/>
            </params>
          </user>
         </users>
        </group>
      </groups>
    </domain>
  </section>
</document>';

error_log("Find sip agent: $user, name: $name client ip: $regip, domain:$domain");
echo $resp;
//error_log("resp: ".$resp);

mysql_close($con);

?>
